package com.yt.server.action;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import com.yt.server.api.IScope;
import com.yt.server.api.action.IActionCall;
import com.yt.server.api.action.IActionCallback;
import com.yt.server.messaging.Packet;

/**
 * 控制器行为
 */
public class ActionCall implements IActionCall, Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5063845913682790208L;

	protected String id; // ID

	protected String actionName; // 业务名

	protected String actionMethodName; // 方法名

	protected Object[] arguments = null; // 参数

	protected byte status = STATUS_PENDING;// 状态

	private Object result; // 返回值

	protected Exception exception; // 返回的异常

	private HashSet<IActionCallback> callbacks = new HashSet<IActionCallback>(); // 回调接口

	protected IScope actionScope; // 当前连接所在的区域

	protected Packet packet; // 处理的数据包

	public ActionCall() {
		super();
	}

	public ActionCall(Packet packet, IScope scope) {
		this(packet.getId(), packet.getActionName(), packet.getMethod(), packet
				.getParams(), scope);
		this.packet = packet;
	}

	public ActionCall(String id, String name, String method, Object[] args,
			IScope scope) {
		this.id = id;
		this.actionName = name;
		this.actionMethodName = method;
		this.arguments = args;
		this.actionScope = scope;
	}

	@Override
	public boolean isSuccess() {
		return (status == STATUS_SUCCESS_RESULT)
				|| (status == STATUS_SUCCESS_NULL)
				|| (status == STATUS_SUCCESS_VOID);
	}

	@Override
	public String getActionMethodName() {
		return actionMethodName;
	}

	@Override
	public String getActionName() {
		return actionName;
	}

	@Override
	public Object[] getArguments() {
		return arguments;
	}

	@Override
	public byte getStatus() {
		return status;
	}

	@Override
	public Exception getException() {
		return exception;
	}

	@Override
	public void setStatus(byte status) {
		this.status = status;
	}

	@Override
	public void setException(Exception exception) {
		this.exception = exception;
	}

	@Override
	public Object getResult() {
		return result;
	}

	@Override
	public void setResult(Object result) {
		this.result = result;
	}

	@Override
	public void registerCallback(IActionCallback callback) {
		callbacks.add(callback);
	}

	@Override
	public Set<IActionCallback> getCallbacks() {
		return callbacks;
	}

	@Override
	public IScope getScope() {
		return actionScope;
	}

	@Override
	public String getId() {
		return id;
	}

	@Override
	public Object getResultPacket() {
		// 处理callbacks中的回调
		packet.setState(status);
		packet.setResult(result);
		packet.setException(exception);
		packet.setScopePath(actionScope.getPath());
		return packet;
	}
}